#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include <string>

#define BACKLOG 5

namespace ns_sock
{

  class Sock
  {
  public:
    static int CreateSocket()
    {
      int lsock = socket(AF_INET, SOCK_STREAM, 0);
      if (lsock < 0){
        std::cerr << "socket error" << std::endl;
        exit(1);
      }
      // 运行创建端口号相同但IP不同的多个socket，解决绑定失败问题
      int opt = 1;
      setsockopt(lsock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
      
      return lsock; 
    }
    static bool Bind(int sock, unsigned short port)
    {
      struct sockaddr_in local;

      memset(&local, 0, sizeof(local));

      local.sin_family = AF_INET;
      local.sin_port = htons(port);
      local.sin_addr.s_addr = INADDR_ANY;

      if (bind(sock,(struct sockaddr*) &local, sizeof(local)) < 0){
        std::cerr << "bind error" << std::endl;
        return false;
      }

      return true;
    }
    static bool Listen(int sock, int backlog = BACKLOG)
    {
      if (listen(sock, backlog) < 0){
        std::cout << "listen error" << std::endl;
        return false;
      }

      return true;
    }
  };
}
